package com.atguigu.tingshu.album.task;

import com.atguigu.tingshu.album.service.AlbumInfoService;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.constant.SystemConstant;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
public class RebuildBloomFilterTask {


    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private AlbumInfoService albumInfoService;

    /**
     * 每月凌晨2点重建/扩容布隆过滤器
     */
    //@Scheduled(cron = "0 0 2 1 * ?")
    public void rebuildBloomFilterTask(){
        //1.获取到原有布隆过滤器对象,得到配置信息: 期望数据量,现有数据量,误判率
        RBloomFilter<Object> oldBloomFilter = redissonClient.getBloomFilter(RedisConstant.ALBUM_BLOOM_FILTER);

        long count = oldBloomFilter.count();
        long expectedInsertions = oldBloomFilter.getExpectedInsertions();
        double falseProbability = oldBloomFilter.getFalseProbability();


        //2.如果现有的数量预估值大于了期望数据量,进行扩容
        if (count >= expectedInsertions){

            //2.1新建布隆过滤器对象
            RBloomFilter<Object> newBloomFilter = redissonClient.getBloomFilter(RedisConstant.ALBUM_BLOOM_FILTER + ":new");
            newBloomFilter.tryInit(expectedInsertions * 2,falseProbability);

            //2.2将现有过审专辑ID添加到新布隆过滤器对象中
            List<Long> albumIdList = albumInfoService.findAlbumIdListByStatus(SystemConstant.ALBUM_STATUS_PASS);

            for (Long id : albumIdList) {
                newBloomFilter.add(id);
            }

            //2.3 删除旧布隆过滤器对象(配置&位图)
            oldBloomFilter.delete();

            //2.4 重命名布隆过滤器
            newBloomFilter.rename(RedisConstant.ALBUM_BLOOM_FILTER);

        }else {
            //3.如果现有的数量预估值大于了期望数据量,进行重建
            //3.1新建布隆过滤器对象
            RBloomFilter<Object> newBloomFilter = redissonClient.getBloomFilter(RedisConstant.ALBUM_BLOOM_FILTER + ":new");
            newBloomFilter.tryInit(expectedInsertions,falseProbability);
            //3.2将现有过审专辑ID添加到新布隆过滤器对象中
            List<Long> albumIdList = albumInfoService.findAlbumIdListByStatus(SystemConstant.ALBUM_STATUS_PASS);

            for (Long id : albumIdList) {
                newBloomFilter.add(id);
            }

            //3.3 删除旧布隆过滤器对象(配置&位图)
            oldBloomFilter.delete();

            //3.4 重命名布隆过滤器
            newBloomFilter.rename(RedisConstant.ALBUM_BLOOM_FILTER);
        }

    }

}
